package com.amox.uitest.adapter;

import java.util.List;

import org.dom4j.Element;
import org.dom4j.Node;

import com.amox.uitest.common.KeyWord;
import com.amox.uitest.common.ReturnException;
import com.amox.uitest.kit.LogKit;
import com.amox.uitest.kit.StrKit;
import com.amox.uitest.kit.XMLKit;
import com.amox.uitest.tcase.BaseTestCase;

public class FuncAdapter extends BaseAdapter<Boolean> {
	
	private ExceptionAdapter exceptionAdapter;
	private FinallyAdapter finallyAdapter;
	
	public FuncAdapter(BaseTestCase uitest) {
		super(uitest);
		exceptionAdapter = new ExceptionAdapter(uitest);
		finallyAdapter = new FinallyAdapter(uitest);
	}
	
	@Override
	public Boolean adapter(Element element) throws Exception {
		
		// define method
		if(element.elements().size() > 0) {
			return define(element);
		}
		
		// call method
		return call(element);
	}
	
	private boolean call(Element element) throws Exception {
		String value = StrKit.me().toSingleLine(element.getStringValue());
		if(value.charAt(0) != '#') {
			LogKit.printLog("The Call Method[0] Should Be Start With [1]", value, "#");
			return false;
		}
		Node classNode = XMLKit.me(uitest).closet(element, KeyWord.clazz.toString());
		Node func = XMLKit.me(uitest).byAttr(classNode, KeyWord.func, KeyWord.id, value.substring(1).trim());
		if(!this.adapter((Element)func)) {
			return false;
		}
		
		return true;
	}
	
	private boolean define(Element element) throws Exception {
		String name = element.attributeValue(KeyWord.id.toString());
		LogKit.printLog("Starting Function[{0}]", name.trim());
		boolean rt = false;
		try {
			List<Element> elements = element.elements();
			for(Element cmdEle : elements) {  
				
				if(KeyWord.exception.toString().equals(cmdEle.getName())
					|| KeyWord.finaly.toString().equals(cmdEle.getName())) {
					continue ;
				}
				
				try {
					rt = execElement(cmdEle);
				} catch (ReturnException e) {
					// if the element's name is return
					return rt;
				}
				
			}
		}catch (Exception e) {
			exceptionAdapter.play(element.element(KeyWord.exception.name()));
		} finally {
			finallyAdapter.play(element.element(KeyWord.finaly.toString()));
		}
		
		LogKit.printLog("Finished Function[{0}]", name);
		return true;
	}
	
}
